<template>
  <div class="allocMenu">
    <el-card class="box-card">
      <div slot="header">
        分配菜单
      </div>
        <el-tree
            v-loading="isLoading"
            ref="tree"
            :data="menus"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="checkedKeys"
            :props="defaultProps">
        </el-tree>
        <el-row style="text-align: center">
          <el-button type="primary" @click="onSave" :disabled="isLoading">保存</el-button>
          <el-button @click="onReset" :disabled="isLoading">重置</el-button>
        </el-row>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getMenuNodeList, setAllocateRoleMenus, getRoleMenus } from '@/services/menu'
import { Tree } from 'element-ui'

export default Vue.extend({
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      menus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeys: [],
      isLoading: false
    }
  },
  created () {
    this.loadMenus()
    this.loadRoleMenus()
  },
  methods: {
    async loadMenus () {
      this.isLoading = true
      const { data } = await getMenuNodeList()
      this.menus = data.data
      this.isLoading = false
    },
    async loadRoleMenus () {
      const { data } = await getRoleMenus(this.roleId)
      this.getcheckedKeys(data.data)
    },
    getcheckedKeys (menus: any) {
      menus.forEach((menu: any) => {
        if (menu.selected) {
          this.checkedKeys = [...this.checkedKeys, menu.id] as any
        }
        if (menu.subMenuList) {
          this.getcheckedKeys(menu.subMenuList)
        }
      })
    },
    onSave () {
      this.$confirm('确认分配菜单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 获取所有已选中的id
        const menuIdList = (this.$refs.tree as Tree).getCheckedKeys()
        const { data } = await setAllocateRoleMenus({
          roleId: this.roleId,
          menuIdList
        })
        if (data.code === '000000') {
          this.$message.success('菜单分配成功')
          this.$router.push({
            name: 'role'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    onReset () {
      (this.$refs.tree as Tree).setCheckedKeys([])
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
